<?php

namespace App\Http\Controllers\Course;

use App\Models\AskAnswer;
use App\Models\CourseClass;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\CourseClassGroup;
use App\Models\OrderCourseClassGroup;
use App\Models\UserOrderGroupRemark;
use App\Models\Course;
use App\Models\CourseClassGroupPeriod;
use App\Models\AskSpecial;
use App\Models\AskZuoye;
use App\Models\AskComment;
use App\User;
use App\Contant\FinanceRecord as FinanceRecordType;
use Excel;

class TrainController extends Controller
{

    public function index(Request $request){
        $courseGroups = CourseClassGroup::paginate(10);
        return view('train.index',['courseGroups'=>$courseGroups]);
    }

    public function courseList(Request $request)
    {
        $id = $request->input('id');
        $courseGroups = CourseClassGroup::where('id', $id)->select('course_class_ids')->first();
        $courseIds = explode(',', $courseGroups->course_class_ids);

        $courses = CourseClass::whereIn('id',$courseIds)->select('id','title')->get();

        return json_encode(['code'=>0,'body'=>view('train.list',['courses'=>$courses])->render()]);
    }

    public function add(Request $request){


        return view('train.add');
    }

    /*
     * 选择课程
     */
    public function selectCourse(Request $request){
        $courses = new CourseClass();
        $title = $request->input('title','');
        if($title){
            $courses  = $courses->where('title','like',"%$title%");
        }
        $courses = $courses->where('state',1)->paginate(8);

        return json_encode(['code'=>0,'body'=>view('train.modal.course',['courses'=>$courses,'title'=>$title])->render()]);
    }

    /*
     * 组合课程创建
     */
    public function postCreate(Request $request){
        $title = $request->input('title');
        $price = $request->input('price');
        $ids = $request->input('course');
        $des = $request->input('description');
        $courseArr = explode(',',$ids);
        $courseClass = CourseClass::where('id',$courseArr[0])->select('user_id')->first();
        
        if($request->input('id')){
            $model = new CourseClassGroup();
            $group = $model->where("id", $request->input('id'))->first();
        }else{
            $group = new CourseClassGroup();
        }
        $group->title = $title;
        $group->price = $price;
        $group->course_class_ids = $ids;
        $group->user_id = $courseClass->user_id;
        $group->description = $des;
        if($group->save()){
            $this->getSessionInfo($request,'success','添加成功');
            return redirect('/train/course');
        }
    }

    public function edit(Request $request){

        $id = $request->input('id');
        $courseGroup = CourseClassGroup::where('id', $id)->select('id','price','title','course_class_ids',"description")->first();
        return view('train.edit',['courseGroup'=>$courseGroup]);
    }


    public function getGroupFlow(Request $request){
        $courseGroup = new OrderCourseClassGroup();
        $userName = $request->input('name','');
        $author = $request->input('author','');
        $id = $request->input('id');
        $dateArr = [1 => '一', 2 => '二', 3 => '三', 4 => '四', 5 => '五', 6 => '六', 7 => '七', 8 => '八', 9 => '九', 10 => '十', 11 => '十一', 12=>'十二'];
        if($id){
            $courseGroup = $courseGroup->where('course_class_group_id',$id);
            $total = OrderCourseClassGroup::where('state',1)->where('course_class_group_id',$id)->count();
        }else{
            $total = OrderCourseClassGroup::where('state',1)->count();
        }
        if($userName){

            $users = User::where('name','like','%'.$userName.'%')->where('is_admin',0)->select('id')->get()->toArray();
            $userArr = [];
            foreach($users as $user){
                $userArr[] = $user['id'];
            }
            $courseGroup = $courseGroup->whereIn('user_id',$userArr);
        }
        if($author){
            $authors = User::where('name','like','%'.$author.'%')->where('is_admin',1)->select('id')->get();
            $groupArr = [];
            foreach($authors as $auth){
                $group = CourseClassGroup::where('user_id',$auth->id)->select('id')->first();
                $groupArr[] = $group->id;
            }
//            if($groupArr){
                $courseGroup = $courseGroup->whereIn('course_class_group_id',$groupArr);
//            }
        }

        $orderGroups = $courseGroup->orderBy('id','desc')->orderBy('stage','desc')->paginate(10);
        return view('finance.groupOrder',['orderGroups'=>$orderGroups,'name'=>$userName,'author'=>$author,'id'=>$id,'total'=>$total,'dateArr'=>$dateArr]);
    }

    public function reserveInfo(Request $request){
        $id = $request->input('id');
        $userRemark = UserOrderGroupRemark::where('user_id',$id)->first();
//        dd($userRemark);
        $years = [1=>"在校学员",2=>"毕业学员未执教",3=>"1年以内",4=>"1-2年",5=>"2-3年",6=>"3-4年",7=>"4-5年",8=>'5年以上'];
        $ways = [1=>"微信公众号",2=>"微信群内",3=>"同学推荐",4=>"导师推荐"];

        return json_encode(['code'=>0,'body'=>view('train.modal.user',['years'=>$years,'ways'=>$ways,'userRemark'=>$userRemark])->render()]);
    }


    public function zuoye($id){
        $special = AskSpecial::where("course_class_group_ids",$id)->first();
        $special_id = $special->id;
        $data = AskZuoye::where("special_id",$special_id)->where("is_question",0)->paginate(10);

        $this->ret['data'] = $data;
        return view("train.ask.zuoye",$this->ret);
    }
    public function answer($qid)
    {
        $question = AskZuoye::where("id", $qid)->first();
        $answer = AskAnswer::where("qid", $qid)->paginate(10);

        $this->ret['question'] = $question;
        $this->ret['data'] = $answer;
        return view("train.ask.answer", $this->ret);
    }

    /*
     * 查看导师点评内容
     * 20190409
     * 卢
     */
    public function teacherCommentGet(Request $request)
    {
        $aid = $request->input("aid");
        $user_id = $request->user()->id;
        $comment = AskComment::where("aid", $aid)->where("user_id", $user_id)->where("level",1)->first();
        if($comment){
            return json_encode(["code"=>1, "msg"=>$comment->content]);
        }else{
            return json_encode(['code'=>0, "msg"=>"暂未评论".$aid.'--'.$user_id]);
        }

    }

    /*
     * 添加导师点评内容
     * 20190409
     * 卢
     */
    public function teacherCommentAdd(Request $request)
    {
        $aid = $request->input("aid");
        $user_id = $request->user()->id;
        $content = $request->input("content");
        $comment = new AskComment();
        $comment->aid = $aid;
        $comment->content = $content;
        $comment->user_id = $user_id;
        $comment->level   = 1;
        $r = $comment->save();
        //$comment = AskComment::where("aid", $aid)->where("user_id", $user_id)->where("level",1)->first();
        if($r){
            return json_encode(["code"=>1, "msg"=>$comment->content]);
        }else{
            return json_encode(['code'=>0, "msg"=>"添加失败请联系管理员".$aid.'--'.$user_id]);
        }
    }

    /*
     * 导出excel
     */
    public function exportGroupLog(Request $request){

        $courseGroup = new OrderCourseClassGroup();
        $userName = $request->input('name','');
        $buyDate = $request->input('buyDate','');
        $id = $request->input('id','');
        $pay = $request->input('pay','');
//        dd($request->all());
        $dateArr = [1 => '一', 2 => '二', 3 => '三', 4 => '四', 5 => '五', 6 => '六', 7 => '七', 8 => '八', 9 => '九', 10 => '十', 11 => '十一', 12=>'十二'];
        if($pay == 'payed'){
            $state = 1;
            $courseGroup = $courseGroup->where('state',1);
        }elseif($pay == 'no'){
            $state = 0;
            $courseGroup = $courseGroup->where('state',0);
        }
        if($id){
            $courseGroup = $courseGroup->where('course_class_group_id',$id);
            $total = OrderCourseClassGroup::where('state',1)->where('course_class_group_id',$id)->count();
        }else{
            $total = OrderCourseClassGroup::where('state',1)->count();
        }
        if($userName){
            $users = User::where('name','like','%'.$userName.'%')->where('is_admin',0)->select('id')->get()->toArray();
            $userArr = [];
            foreach($users as $user){
                $userArr[] = $user['id'];
            }
            $courseGroup = $courseGroup->whereIn('user_id',$userArr);
        }
        $start = '';
        if($buyDate){
            $start = $this->getBuyedDate($buyDate)['start'];
            $end = $this->getBuyedDate($buyDate)['end'];
        }
//        dd($start,$end);
        if($start && $buyDate != 'all'){

            $courseGroup = $courseGroup->where('created_at','>=',$start)->where('created_at','<=',$end);
        }
//        dd($start,$end);
        $courseGroup = $courseGroup->orderBy('id','desc')->get();
//        dd($courseGroup);
        $financeData = ['付费者','导师','期数','手机号','支付方式','是否支付','付款时间','金额'];
        $total = 0;
        $info = [];
        foreach($courseGroup as $k=>$record) {
            if ($record->user) {
                $info[$k][] = $record->user->nickname;
            } else {
                $info[$k][] = '';
            }
            if ($record->courseGroup && $record->courseGroup->author) {
                $info[$k][] = $record->courseGroup->author->name;
            } else {
                $info[$k][] = '';
            }
            if (empty($record->stage)) {
                if (strtotime('2019-03-25 23:59:59') > strtotime($record->created_at)) {
                    if (strtotime($record->created_at) > strtotime('2019-03-23 23:59:59')) {
                        if ($record->price == 599) {
                            $info[$k][] = '一期';
                        } else {
                            $info[$k][] = '二期';
                        }
                    } else {
                        $info[$k][] = '一期';
                    }
                } else {
                    $info[$k][] = '一期';
                }
            } else {
                $info[$k][] = $dateArr[$record->stage] . '期';
            }

            if ($record->user) {
                $info[$k][] = "" . $record->user->mobile . "";
            } else {
                $info[$k][] = '';
            }
            $info[$k][] = FinanceRecordType::trans($record->payfrom);
            $info[$k][] = date('Y-m-d H:i:s', strtotime($record->created_at));
            $info[$k][] = $record->price;
            $info[$k][] = $record->courseGroup->title;
            if($record->state == 1){
                $total += $record->price;
            }
        }
//        dd($info);
        array_unshift($info,$financeData);
//        dd($info);

        $data['list'] = $info;
        $data['total'] = $total;
//        dd($data);
        Excel::create('购买记录', function($excel) use($data) {
//          )  function($cell) {
//                    $cell->setValue('支付总金额');
//                }$data;
            $excel->sheet('流水', function($sheet) use($data) {
                $infos = $data['list'];
                $length = count($infos);
                $sheet->setWidth(array(
                    'A' =>  20,
                    'B' =>  20,
                    'C' => 20,
                    'D' => 20,
                    'E' => 20,
                    'F' => 20,
                    'G'=>20,
                    'H'=>70
                ));

                for($i=0;$i<$length;$i++){
                    $sheet->row($i+1,$infos[$i]);
                }

//                dd($length+1);
                $sheet->mergeCells('A'.($length+1).':G'.($length+1));
                $sheet->row($length+1, ['总支付：']);
                $total = $data['total'];
                $sheet->cell('H'.($length+1),function($cell) use($total){
                    $cell->setValue($total);
                });

//                $sheet->row($length,['总计',$data['total']]);
//                dd(['总计',$data['total']]);

            });
        })->export('xls');
    }

    public function getBuyedDate($time){
        switch($time) {
            case 'ten':
                $end = date('Y-m-d 23:59:59');
                $start = date('Y-m-d', time() - 86400 * 9);
                break;
            case 'thirty':
                $end = date('Y-m-d 23:59:59');
                $start = date('Y-m-d', time() - 86400 * 9);
                break;
            case 'sixty':
                $end = $end = date('Y-m-d 23:59:59');
                $start = date('Y-m-d', time() - 86400 * 59);
                break;
            default:
                $end = '';
                $start = '';
        }
        return ['start'=>$start,'end'=>$end];


    }

    /*
    *期数设置
    */
    public function periods(Request $request){
        $id = $request->input('id','');
        $periods = CourseClassGroupPeriod::where('course_class_group_id',$id)->orderBy('created_at','desc')->paginate(10);

        return view('train.periods',['periods'=>$periods,'id'=>$id]);

    }

    /*
     * 添加期数
     */
    public function addPeriods(Request $request){
        $id = $request->input('id','');
        return view('train.addPeriod',['id'=>$id]);
    }
    public function createPeriods(Request $request){
        $group_id = $request->input('groupId');
        $name = $request->input('name');
        $begin_time = $request->input('startTime');
        $per = CourseClassGroupPeriod::orderBy('id','desc')->first();
        if($per){
            $num = $per->stage +1;
        }else{
            $num = 1;
        }
        $period = new CourseClassGroupPeriod();
        $period->name = $name;
        $period->begin_time = $begin_time;
        $period->course_class_group_id = $group_id;
        $period->stage = $num;

        $period->save();
        $this->getSessionInfo($request,'success','添加成功');
        return redirect('/train/periods?id='.$group_id);
    }

    public function editPeriods(Request $request){
        $id = $request->input('id');
        $period = CourseClassGroupPeriod::where('id',$id)->first();
        return view('train.editPeriod',['period'=>$period]);
    }

    public function poseEditPeriods(Request $request){
        $id = $request->input('id');
        $name = $request->input('name');
        $begin_time = $request->input('startTime');
        $period = CourseClassGroupPeriod::where('id',$id)->first();
        $period->name = $name;
        $period->begin_time = $begin_time;
        $period->save();
        $this->getSessionInfo($request,'success','添加成功');
        return redirect('/train/periods?id='.$period->course_class_group_id);
    }

    public function setShow(Request $request){
        $id = $request->input('id');
        $is_show = $request->input('is_show');
        $period = CourseClassGroupPeriod::where('id',$id)->first();
        $period->is_show = $is_show;
        $period->save();
        return $this->getMessage(0,'设置成功');
    }
}